<?php

namespace app\admin\controller\meet;

use app\admin\model\User;
use app\common\controller\Backend;
use Exception;
use fast\Http;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 门店管理
 *
 * @icon fa fa-circle-o
 */
class Store extends Backend
{
    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['map', 'suggestion', 'fans'];

    /**
     * Store模型对象
     * @var \app\admin\model\meet\Store
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\meet\Store;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $row = $this->model->get($this->model::STORE_ID);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
            if (empty($row['longitude']) || empty($row['latitude'])) {
                $row['location'] = '';
            } else {
                $row['location'] = $row['longitude'] . ',' . $row['latitude'];
            }

            $receive_users = [];

            if (!empty($row['receive_user_ids'])) {
                $user_ids_arr = explode(',', $row['receive_user_ids']);
                $receive_users = User::with(['third', 'third.fans'])->where('id', 'in', $user_ids_arr)->select();

                foreach ($receive_users as $key => $value) {
                    if (!empty($value['third'])) {
                        if ($value['third']['fans']) {
                            $value->is_subscribe = $value->third->fans->is_subscribe;
                            $value->subscribe_time = $value->third->fans->subscribe_time;
                            $value->openid = $value->third->fans->openid;
                            continue;
                        }
                    }

                    $value->is_subscribe = 0;
                    $value->subscribe_time = '';
                    $value->openid = '';
                }
            }

            $row['receive_users'] = json_encode($receive_users);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $province = $this->request->post("province");
        $city = $this->request->post("city");
        $area = $this->request->post("area");

        if (empty($params['business_hours'])) {
            $this->error(__('Business hours cannot be empty'));
        }

        $business_hours = explode('-', $params['business_hours']);
        if (count($business_hours) <= 0) {
            $this->error(__('Incorrect format of business hours'));
        }

        if ((strtotime($business_hours[0]) === false) || (strtotime($business_hours[1]) === false)) {
            $this->error(__('Incorrect format of business hours'));
        }

        if (strtotime($business_hours[0]) >= strtotime($business_hours[1])) {
            $this->error(__('The business start time needs to be earlier than the business end time!'));
        }

        if (strtotime($business_hours[1]) > strtotime("24:00")) {
            $this->error(__('The maximum closing time for business is 24:00'));
        }

        $result = false;
        Db::startTrans();
        try {
            if (isset($params['users']) && !empty($params['users'])) {
                $params['receive_user_ids'] = implode(',', array_column($params['users'], 'id'));
            } else {
                $params['receive_user_ids'] = '';
            }

            if (isset($params['time_interval']) && !empty($params['time_interval'])) {
                $params['time_interval'] = implode(',', $params['time_interval']);
            }else{
                $params['time_interval'] = '';
            }

            $params['province_id'] = $province;
            $params['city_id'] = $city;
            $params['county_id'] = $area;
            $location = explode(',', $params['location']);
            $params['longitude'] = $location[0];
            $params['latitude'] = $location[1];
            unset($params['location']);

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 地图
     * @internal
     */
    public function map()
    {
        $longitude = $this->request->request('longitude', '');
        $latitude = $this->request->request('latitude', '');

        $this->view->assign('latitude', $latitude);
        $this->view->assign('longitude', $longitude);
        $this->view->assign('tencent_map_key', \app\common\model\meet\Config::getConfigByName('tencent_map_key')['value']);

        return $this->view->fetch();
    }

    /**
     * 地图搜索
     * @internal
     */
    public function suggestion()
    {
        //搜索字段
        $word = (array)$this->request->request("q_word/a");
        $page_index = $this->request->request('pageNumber/d');
        $page_size = $this->request->request('pageSize/d');

        $param = [
            'keyword' => $word[0],
            'key' => \app\common\model\meet\Config::getConfigByName('tencent_map_key')['value'],
            'page_index' => $page_index,
            'page_size' => $page_size
        ];

        $request = Http::get('https://apis.map.qq.com/ws/place/v1/suggestion', $param);

        $result = json_decode($request, true);

        if ($result['status'] == 0 && !empty($result['data'])) {
            $list = $result['data'];

            foreach ($list as $key => $value) {
                $list[$key]['title'] = $value['province'] . $value['city'] . $value['district'] . $value['title'];
                $list[$key]['pid'] = 0;
            }
            return json(['list' => $list, 'total' => $result['count']]);
        } else {
            return json(['list' => [], 'total' => 0]);
        }
    }

    /**
     * 微信粉丝
     *
     * @internal
     */
    public function fans()
    {
        $this->model = new User();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['third', 'third.fans'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        if ($list->items()) {
            foreach ($list as $key => $value) {
                if (!empty($value['third'])) {
                    if ($value['third']['fans']) {
                        $value->is_subscribe = $value->third->fans->is_subscribe;
                        $value->subscribe_time = $value->third->fans->subscribe_time;
                        $value->openid = $value->third->fans->openid;
                        continue;
                    }
                }

                $value->is_subscribe = 0;
                $value->subscribe_time = '';
                $value->openid = '';
            }
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
}
